package net.ufrog.common.spring;

import net.ufrog.common.exception.ServiceException;
import net.ufrog.common.utils.Cryptos;
import org.springframework.util.DefaultPropertiesPersister;

import java.io.*;
import java.util.List;
import java.util.Properties;

/**
 * @author ultrafrog, ufrog.net@gmail.com
 * @version 0.1, 2016-04-19
 * @since 0.1
 */
public class DecryptPropertiesPersister extends DefaultPropertiesPersister {

    private List<String> keys;

    @Override
    public void load(Properties props, InputStream is) throws IOException {
        try (OutputStream os = new ByteArrayOutputStream()) {
            Properties properties = new Properties();
            properties.load(is);
            keys.stream().filter(key -> properties.get(key) != null).forEach(key -> {
                String decrypted = Cryptos.decryptAES(properties.getProperty(key));
                properties.setProperty(key, decrypted);
            });
            properties.store(os, "");
            super.load(props, toInputStream(os));
        }
    }

    /**
     * @return 键值列表
     */
    public List<String> getKeys() {
        return keys;
    }

    /**
     * @param keys 键值列表
     */
    public void setKeys(List<String> keys) {
        this.keys = keys;
    }

    /**
     * @param outputStream 输出流
     * @return 输入流
     */
    private InputStream toInputStream(OutputStream outputStream) {
        if (outputStream instanceof ByteArrayOutputStream) {
            ByteArrayOutputStream baos = (ByteArrayOutputStream) outputStream;
            return new ByteArrayInputStream(baos.toByteArray());
        } else {
            throw new ServiceException("cannot to input stream from " + outputStream.getClass().getName() + ".");
        }
    }
}
